package es

import (
	"bytes"
	"context"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"srv/model/mysql"
	"strconv"
)

//	func Hight(keyword string) (goodList []*srv.GoodListPt, err error) {
//		query := map[string]interface{}{}
//		if keyword != "" {
//			query = map[string]interface{}{
//				"query": map[string]interface{}{
//					"match": map[string]interface{}{
//						"GoodName": keyword,
//					},
//				},
//			}
//		} else {
//			query = map[string]interface{}{
//				"query": map[string]interface{}{
//					"match_all": map[string]interface{}{},
//				},
//			}
//		}
//		var buf bytes.Buffer
//		json.NewEncoder(&buf).Encode(query)
//		return
//	}
func EsAdd(goods []mysql.Good) {
	for _, title := range goods {
		wg.Add(1)

		go func(title mysql.Good) {
			defer wg.Done()
			// Build the request body.
			data, err := json.Marshal(title)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "goods",
				DocumentID: strconv.Itoa(int(title.ID)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()
		}(title)
	}
	wg.Wait()
}

func EsFind(goodName string) () {
	var buf bytes.Buffer
	query := map[string]interface{}{}
	if goodName == "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"Title": goodName,
				},
			},
		}
	}
	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	// Perform the search request.
	res, err := Es.Search(
		Es.Search.WithContext(context.Background()),
		Es.Search.WithIndex("goods"),
		Es.Search.WithBody(&buf),
		Es.Search.WithTrackTotalHits(true),
		Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	var r map[string]interface{}
	json.NewDecoder(res.Body).Decode(&r)

	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		m := hit.(map[string]interface{})["_source"].(map[string]interface{})

	}

}
